import { useAppStore } from '@/store/app';
import { useApprovalProvide } from '..';

/**
 *
 * @returns taskId 审批任务提交时的id
 */
export const useTaskId = () => {
  const { progressData } = useApprovalProvide();
  const appStore = useAppStore();
  const taskId = computed(() => {
    let taskId = '';
    if (!progressData.value?.taskActivities?.length) return taskId;
    const { taskActivities, historicProcessInstance } = progressData.value;
    // 不是审批中状态直接返回空
    if (historicProcessInstance?.approvalConclusion !== 'PROCESSING') return taskId;

    taskActivities?.forEach((item) => {
      item.userTasks?.forEach((task) => {
        const { approvalStatus, assigneeUsers } = task;

        // 审批中的任务
        if (!approvalStatus && assigneeUsers) {
          assigneeUsers.forEach((user) => {
            const isHandler = appStore.mcisaas.userId === user.userId;
            /* 避免被后面的任务覆盖 && 当前审批的操作人 */
            if (!taskId && isHandler) {
              taskId = task.id || '';
            }
          });
        }
      });
    });
    return taskId;
  });
  return {
    taskId
  };
};

export const useGetTaskId = (data: any) => {
  const progressData = useApprovalProvide()?.progressData?.value || data;
  // const { progressData } = useApprovalProvide();
  const appStore = useAppStore();
  let taskId = '';
  if (!progressData?.taskActivities?.length) return taskId;
  const { taskActivities, historicProcessInstance } = progressData;
  // 不是审批中状态直接返回空
  if (historicProcessInstance?.approvalConclusion !== 'PROCESSING') return taskId;
  taskActivities?.forEach((item) => {
    item.userTasks?.forEach((task) => {
      const { approvalStatus, assigneeUsers } = task;
      // 审批中的任务
      if (!approvalStatus && assigneeUsers) {
        assigneeUsers.forEach((user) => {
          const isHandler = appStore.mcisaas?.userBaseId === user.userId;
          /* 避免被后面的任务覆盖 && 当前审批的操作人 */
          if (!taskId && isHandler) {
            taskId = task.id || '';
          }
        });
      }
    });
  });
  return taskId;
};
